package com.black.cat.seed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.black.cat.seed.common.ApiResponse;
import com.black.cat.seed.entity.BaseEntity;
import com.black.cat.seed.utils.SecurityUtil;
import com.black.cat.seed.vo.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @Author blackcat
 * @create 2021/3/28 23:05
 * @version: 1.0
 * @description:
 */
public abstract class BaseController<T extends BaseEntity,S extends IService<T>> {

    @Autowired
    protected S baseService;

    @GetMapping("/get")
    public ApiResponse<T> get(Long id) {
        return ApiResponse.ofSuccess(baseService.getById(id));
    }

    @GetMapping("page")
    public ApiResponse<List<T>> page(T entity, Integer pageNo, Integer pageSize) {
        IPage<T> page = new Page<>(pageNo, pageSize);
        UserPrincipal user = SecurityUtil.getCurrentUser();
        List<String> roles = user.getRoles();
        if(CollectionUtils.isEmpty(roles)){
            entity.setCreator(user.getId().toString());
        }else{
            if(!roles.contains("管理员")){
                entity.setCreator(user.getId().toString());
            }
        }
        IPage<T> list = baseService.page(page, new QueryWrapper<>(entity));
        return ApiResponse.ofSuccess(list.getRecords(), list.getTotal());
    }

    @PostMapping("create")
    public ApiResponse<Boolean> create(T entity) {
        UserPrincipal user = SecurityUtil.getCurrentUser();
        entity.setCreator(user.getId().toString());
        entity.setUpdator(user.getId().toString());
        return ApiResponse.ofSuccess(baseService.save(entity));
    }

    @PostMapping("update")
    public ApiResponse<Boolean> update(@Validated() T entity) {
        UserPrincipal user = SecurityUtil.getCurrentUser();
        entity.setUpdator(user.getId().toString());
        return ApiResponse.ofSuccess(baseService.updateById(entity));
    }

    @PostMapping("/delete")
    public ApiResponse<Boolean> delete(Long id) {
        return ApiResponse.ofSuccess(baseService.removeById(id));
    }
}
